<template>
  <view class="clan-page">
    <!-- 创建宗亲荟表单 -->
    <!-- <clanSionFrom @closeCreateForm="closeCreateForm" v-if="showCreateFormFlag" /> -->
    <view>
      <view>
        <!-- 宗亲荟信息 -->
        <view class="clan-info">
          <view class="info-header">
            <view class="info-title">宗亲荟信息</view>
            <view
              plain
              size="small"
              class="apply-btn"
              @click="handleApply"
            >
              申请入荟
            </view>
          </view>
          <view class="info-list">
            <view class="info-item">
              <!-- <text class="item-label">简介</text> -->
              <div class="item-content">
                <div v-if="clanAssoInfo?.history" class="content-paragraph" v-html="clanAssoInfo.history"></div>
                <text v-else>暂无简介信息</text>
              </div>
            </view>
          </view>
        </view>
        <!-- 宗亲荟内容tabs -->
        <ClanTabs
          :award-list="awardList"
          :event-list="eventList"
          :clanId="clanAssoInfo?.id"
          @view-member="viewMemberDetail"
          @view-more-events="viewMoreEvents"
          @view-event="viewEventDetail"
        />

        <!-- 位置信息 -->
        <view class="location-section">
          <view class="location-header">
            <text class="location-title">位置信息</text>
          </view>
          <view class="location-content">
            <text class="location-text">{{ clanAssoInfo?.location || "暂无位置信息" }}</text>
            <view class="map-container">
              <Amap
                :center="mapCenter"
                :zoom="15"
                :markers="mapMarkers"
                container-style="width:100%;height:400rpx;border-radius:8rpx;margin-top:16rpx;"
              />
            </view>
          </view>
        </view>
      </view>

      <!-- 提示弹窗 -->
      <view v-if="showPopup" class="popup-mask" @click="showPopup = false"></view>
      <view v-if="showPopup" class="popup-content">
        <view class="popup-title">提交成功</view>
        <view class="popup-message">
          您的宗亲荟申请已提交成功，我们荟尽快审核，请耐心等待通知。
        </view>
        <button class="popup-btn" @click="confirmSuccess">确定</button>
      </view>

      <!-- 申请人员基本信息弹窗组件 -->
      <MemberDetailPopup
        v-model:visible="showMemberDetail"
        :member="currentMember"
        @approve="handleApprove"
        @reject="handleReject"
      />
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import Amap from "@/components/map/Amap.vue";
import ClanAssociationAPI from "@/api/genealogy/clanAssociation";
// import errorManage from "./component/errorManage.vue";
import MemberDetailPopup from "./component/MemberDetailPopup.vue";
import ClanMemberAPI from "@/api/genealogy/clanMember";
import ClanTabs from "./component/ClanTabs.vue";
// import clanSionFrom from "@/pages/work/clan/component/component/clanSionFrom.vue";

// 处理HTML内容，将p标签转换为带有content-p类的div标签
const processHtmlContent = (html: string): string => {
  if (!html) return '';
  // 将<p>标签替换为<div class="content-p">
  let processedHtml = html.replace(/<p[^>]*>/gi, '<div class="content-p">');
  // 将</p>标签替换为</div>
  processedHtml = processedHtml.replace(/<\/p>/gi, '</div>');
  return processedHtml;
};

// 用户信息接口
interface UserInfo {
  id?: string;
  username?: string;
  areaCodeScope?: Number;
  [key: string]: any;
}

// 定义宗亲荟信息接口
interface ClanAssociationInfo {
  id?: string;
  name?: string;
  location?: string;
  address?: string;
  longitude?: number;
  latitude?: number;
  logo?: string;
  description?: string;
  history?: string;
  hasJoined?: string;
  [key: string]: any;
}
// 创建宗亲荟荟表单判断
const showCreateFormFlag = ref(false);
const formRef = ref();
// Loading状态
const loading = ref(true);
// 是否存在宗亲荟
const isClan = ref(false);
// 判断是否为宗亲荟
const isClanFlag = ref(false);
// 荣誉墙数据
const awardList = ref([
  { year: "2023", name: "优秀宗亲荟组织" },
  { year: "2022", name: "文化传承示范基地" },
  { year: "2020", name: "慈善公益先进单位" },
  { year: "2019", name: "优秀传统文化推广奖" },
  { year: "2018", name: "社区和谐建设贡献奖" },
]);

const clanAssoInfo = ref<ClanAssociationInfo>({});
const userInfo = ref<UserInfo>({});

const handleApply = () => {
  uni.navigateTo({
    url: `/pages/work/clan/apply?type=apply&clanId=${clanAssoInfo.value.id}`,
  });
};
// const handleAddClanMember = () => {
//   uni.navigateTo({
//     url: '/pages/work/clan/apply?type=join'
//   })
// }
// 子组件关闭宗亲表单
const closeCreateForm = () => {
  showCreateFormFlag.value = false;
};
// 获取用户信息
const getUserInfo = () => {
  try {
    const userInfoStr = uni.getStorageSync("user-info");
    if (userInfoStr) {
      // 如果 userInfoStr 是字符串，需要解析为对象
      if (typeof userInfoStr === "string") {
        userInfo.value = JSON.parse(userInfoStr);
      } else {
        userInfo.value = userInfoStr;
      }
      console.log("用户信息:", userInfo.value);
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
  }
};

// 判断是否存在宗亲荟信息
const hasClanInfo = computed(() => {
  console.log("判断是否存在宗亲荟信息:", clanAssoInfo.value);
  return (
    (clanAssoInfo.value && Object.keys(clanAssoInfo.value).length > 0 && clanAssoInfo.value.id) ||
    isClan.value
  );
});

// 成员数据
const memberList = ref([
  {
    id: "1",
    name: "李岗华",
    role: "荟长",
    avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
    company: "江西康华企业发展集团有限公司",
    position: "董事长",
  },
  {
    id: "2",
    name: "李光荣",
    role: "名誉荟长",
    avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
    company: "江西省越光电缆股份有限公司",
    position: "董事长",
  },
  {
    id: "3",
    name: "李良斌",
    role: "名誉荟长",
    avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
    company: "江西赣锋锂业股份有限公司",
    position: "董事长",
  },
  {
    id: "4",
    name: "李文华",
    role: "名誉荟长",
    avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
    company: "湾里管理局招贤便民服务中心",
    position: "七级职员",
  },
  {
    id: "5",
    name: "李俊",
    role: "执行荟长",
    avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
    company: "江西华正机电设备工程有限公司",
    position: "董事长",
  },
]);

// 活动数据
const eventList = ref([
  {
    id: "1",
    title: "2024年宗亲春节联欢荟",
    time: "2024-02-10 18:30",
    location: "博阳大酒店宴荟厅",
    image: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/0a345d867e234edca9048c330a16887b.png",
  },
  {
    id: "2",
    title: "宗亲荟第三届理事荟就职典礼",
    time: "2024-03-15 10:00",
    location: "江西荟议中心",
    image: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/0a345d867e234edca9048c330a16887b.png",
  },
  {
    id: "3",
    title: "宗亲荟文化传承研讨荟",
    time: "2024-04-20 14:00",
    location: "博阳文化中心",
    image: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/0a345d867e234edca9048c330a16887b.png",
  },
]);

// 获取宗亲荟信息
const getClanAssociation = async (id: any) => {
  try {
    loading.value = true; // 开始加载
    const res = await ClanAssociationAPI.getClanInfo(id);

    // 如果 res 为 null 或 undefined，设置为空对象
    if (res === null || res === undefined) {
      clanAssoInfo.value = {} as ClanAssociationInfo;
    } else {
      clanAssoInfo.value = res as ClanAssociationInfo;

      // 处理HTML内容，将p标签转换为带有content-p类的div标签
      if (clanAssoInfo.value.history) {
        clanAssoInfo.value.history = processHtmlContent(clanAssoInfo.value.history);
      }

      // 确保地址字段被正确赋值
      if ((res as any).address) {
        clanAssoInfo.value.location = (res as any).address;
      }

      // 如果获取到宗亲荟信息，更新地图标记
      if ((res as any).longitude && (res as any).latitude) {
        mapCenter.value = [(res as any).longitude, (res as any).latitude];
        mapMarkers.value = [
          {
            position: [(res as any).longitude, (res as any).latitude],
            title: (res as any).name || "江西博阳李家宗亲荟",
            icon: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/2a6a85534eea442cb1a7864c503e9d67.png",
            info: {
              title: (res as any).name || "江西博阳李家宗亲荟",
              address:
                (res as any).address ||
                (res as any).location ||
                "江西省南昌市青山湖区东华大道康华电商大厦二楼",
              coverImage: (res as any).logo || "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
            },
          },
        ];
      }

      // 如果获取到成员列表，更新宗亲谱数据
      if ((res as any).memberList && Array.isArray((res as any).memberList)) {
        memberList.value = (res as any).memberList
          .filter((member: any) => member.status !== 0)
          .map((member: any) => ({
            id: member.clanMemberId || "",
            name: member.clanMemberName || "",
            avatar: member.photoUrl || "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
            company: member.companyName || "",
            role: member.companyPosition || "",
            position: member.position || "",
          }));

        // 从 memberList 中筛选待审核成员（status 为 pending 的成员）
        const pendingMembers = (res as any).memberList
          .filter((member: any) => member.status === 0)
          .map((member: any) => ({
            id: member.clanMemberId || "",
            name: member.clanMemberName || "",
            avatar: member.photoUrl || "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
            company: member.companyName || "",
            role: member.companyPosition || "",
            position: member.position || "",
            status: member.status || 0,
          }));

        pendingMemberList.value = pendingMembers;
        console.log("待审核成员列表:", pendingMemberList.value);
      }
    }
  } catch (error) {
    console.error("获取宗亲荟信息失败:", error);
    clanAssoInfo.value = {} as ClanAssociationInfo;
    setTimeout(() => {
      uni.navigateBack({
        delta: 1,
      });
    }, 1500);
  } finally {
    loading.value = false; // 结束加载
  }
};

// 待入谱成员数据
interface PendingMember {
  id: string;
  name: string;
  role: string;
  avatar: string;
  company: string;
  position: string;
  status: number;
  reason: string;
}

const pendingMemberList = ref<PendingMember[]>([]);

// 弹窗控制
const showPopup = ref(false);
const showMemberDetail = ref(false);
const currentMember = ref<PendingMember | null>(null);

// 处理待审核成员操作
const handlePendingMember = (member: PendingMember) => {
  console.log("处理待审核成员:", member);
  showMemberDetail.value = true;
  currentMember.value = member;
};

// 处理通过申请
const handleApprove = (member: PendingMember) => {
  ClanMemberAPI.doAudit({
    id: member.id,
    reason: member.reason,
    status: 1,
  }).then((res) => {
    console.log("处理通过申请:", res);
  });
  // 这里应该调用API处理通过申请
  setTimeout(() => {
    uni.hideLoading();
    uni.showToast({ title: "已通过申请", icon: "success" });
    showMemberDetail.value = false;
    // 重新获取数据
    getClanAssociation();
  }, 1000);
};

// 处理拒绝申请
const handleReject = (member: PendingMember) => {
  ClanMemberAPI.doAudit({
    id: member.id,
    reason: member.reason,
    status: 2,
  }).then((res) => {
    console.log("处理拒绝申请:", res);
  });
  uni.showLoading({ title: "处理中..." });
  // 这里应该调用API处理拒绝申请
  setTimeout(() => {
    uni.hideLoading();
    uni.showToast({ title: "已拒绝申请", icon: "none" });
    showMemberDetail.value = false;
    // 重新获取数据
    getClanAssociation();
  }, 100);
};

// 确认成功
const confirmSuccess = () => {
  showPopup.value = false;
  uni.navigateBack();
};

// 地图数据
const mapCenter = ref([115.858197, 28.682892]); // 康华电商大厦位置
const mapMarkers = ref([
  {
    position: [115.858197, 28.682892],
    title: "江西博阳李家宗亲荟",
    icon: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/2a6a85534eea442cb1a7864c503e9d67.png",
    info: {
      title: "江西博阳李家宗亲荟",
      address: "江西省南昌市青山湖区东华大道康华电商大厦二楼",
      coverImage: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
    },
  },
]);

// 查看成员详情
const viewMemberDetail = (member: any) => {
  console.log("跳转到成员详情", member);
  uni.navigateTo({
    url: `/pages/mine/profile/card?id=${member.id}&source=clan`,
  });
};

// 查看活动详情
const viewEventDetail = (event: any) => {
  uni.navigateTo({
    url: `/pages/work/clan/event?id=${event.id}`,
  });
};

// 查看更多活动
const viewMoreEvents = () => {
  uni.navigateTo({
    url: "/pages/work/clan/events",
  });
};

// 查看待入谱成员详情
const viewPendingMember = (member: any) => {
  uni.navigateTo({
    url: `/pages/work/clan/pending-detail?id=${member.id}`,
  });
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    0: "待审核",
    approved: "已通过",
    rejected: "已拒绝",
  };
  return statusMap[status] || "未知状态";
};

// 刷新宗亲荟信息
const handleRefresh = () => {
  console.log("收到刷新事件，重新获取宗亲荟信息");
  getClanAssociation();
};
// 获取单个宗亲荟信息
// const getClanInfo = (id: any) => {
//   ClanAssociationAPI.getClanInfo(id).then((res: any) => {
//     clanAssoInfo.value = res.data;
//   })
// }
const initClanOnLoad = (query: any) => {
  // 修复判断逻辑，正确解析传递的参数
  if (query.checkMyClan !== undefined) {
    // 将字符串转换为布尔值
    isClanFlag.value =
      query.checkMyClan === "true" || query.checkMyClan === "1" || query.checkMyClan === 1;
  }
  // 是否需要创建宗亲荟
  if (query.type == "create") {
    showCreateFormFlag.value = true;
  }
  if (query.clanId) {
    isClan.value = true;
    getClanAssociation(query.clanId);
  }
};

onMounted(() => {
  getUserInfo();
  // getClanAssociation()
});
onLoad((query: any) => {
  initClanOnLoad(query);
});
</script>

<style lang="scss">
/* 创建表单样式 */
.create-form-section {
  width: 100%;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background-color: #f8f9fa;
}

.form-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.back-btn {
  padding: 12rpx 24rpx;
  border-radius: 20rpx;
  background-color: #f0f0f0;
  transition: all 0.3s ease;
}

.back-btn:active {
  background-color: #e0e0e0;
}

.back-text {
  font-size: 26rpx;
  color: #666;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
  background-color: #f8f9fa;
}

.form-actions .action-btn {
  flex: 1;
  margin: 0;
}
.action-btn {
  padding: 24rpx 40rpx;
  border-radius: 50rpx;
  text-align: center;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.action-btn.primary {
  background: #4d80f0;
  border: 2rpx solid rgba(255, 255, 255, 0.2);
  color: #ffffff;
}

.action-btn.secondary {
  background: rgba(255, 255, 255, 0.2);
  border: 2rpx solid rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(10rpx);
}

.action-btn:active {
  transform: scale(0.95);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

.btn-text {
  font-size: 32rpx;
  font-weight: 600;
}
.tips-section {
  width: 100%;
  max-width: 600rpx;
}

.tip-item {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
  padding: 20rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16rpx;
  backdrop-filter: blur(10rpx);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
}

.tip-icon {
  font-size: 32rpx;
  margin-right: 16rpx;
  flex-shrink: 0;
}

.tip-text {
  font-size: 26rpx;
  line-height: 1.4;
}
.clan-page {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 30rpx;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #f8f8f8;
}

.loading-text {
  margin-top: 20rpx;
  color: #999;
  font-size: 28rpx;
}

.clan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;

  .header-content {
    display: flex;
    align-items: center;
  }

  .clan-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-right: 16rpx;
  }

  .clan-tag {
    font-size: 22rpx;
    color: #fff;
    background-color: #67c23a;
    padding: 6rpx 12rpx;
    border-radius: 6rpx;
  }

  .header-actions {
    display: flex;
    gap: 16rpx;
    align-items: center;
  }

  .create-btn {
    font-size: 28rpx;
    color: #fff;
    background-color: #67c23a;
    padding: 12rpx 30rpx;
    border-radius: 30rpx;
  }
}

.clan-info {
  margin-top: 20rpx;
  padding: 0;
  background-color: #fff;

  .info-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    border-bottom: 4rpx solid #1989fa;
    padding: 20rpx 30rpx;
    position: relative;

    &::after {
      content: "";
      position: absolute;
      bottom: -4rpx;
      left: 0;
      width: 60rpx;
      height: 4rpx;
      background-color: #1989fa;
    }
  }

  .info-list {
    padding: 20rpx 30rpx;
  }

  .info-item {
    display: flex;
    padding: 16rpx 0;
    border-bottom: 1rpx solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }

    .item-label {
      width: 120rpx;
      font-size: 28rpx;
      color: #666;
      flex-shrink: 0;
    }

    .item-content {
      flex: 1;
      font-size: 28rpx;
      color: #333;
      line-height: 1.6;
      width: 100%;
      .content-paragraph {
          .content-p {
            margin: 0;
            padding: 0;
            line-height: 1.6;
          }
          img {
            width: 100% !important;
          }
        }
    }

    .location-content {
      flex: 1;

      .location-text {
        font-size: 28rpx;
        color: #333;
        line-height: 1.6;
        margin-bottom: 16rpx;
      }

      .map-container {
        width: 100%;
        border-radius: 8rpx;
        overflow: hidden;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      }
    }
  }

  .info-header {
    position: relative;

    .apply-btn {
      position: absolute;
      top: 0.5rem;
      right: 20rpx;
      font-size: 28rpx;
      color: #fff !important;
      background-color: #1989fa;
      padding: 12rpx 30rpx;
      border-radius: 30rpx;
    }
  }
}

.pending-members {
  margin-top: 20rpx;
  background-color: #fff;
  padding: 20rpx;

  .pending-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 20rpx;
    margin-bottom: 20rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .pending-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .pending-count {
      font-size: 26rpx;
      color: #1989fa;
      background-color: #f0f8ff;
      padding: 6rpx 12rpx;
      border-radius: 20rpx;
    }
  }

  .pending-list {
    .pending-item {
      display: flex;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f5f5f5;

      &:last-child {
        border-bottom: none;
      }

      .pending-avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-right: 20rpx;
        flex-shrink: 0;
        background-color: #f5f5f5;
      }

      .pending-info {
        flex: 1;
        display: flex;
        flex-direction: column;

        .pending-name {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 8rpx;
        }

        .pending-relation {
          font-size: 24rpx;
          color: #666;
          margin-bottom: 6rpx;
        }

        .pending-apply-time {
          font-size: 22rpx;
          color: #999;
        }
      }

      .pending-status {
        flex-shrink: 0;

        .status-badge {
          padding: 6rpx 16rpx;
          border-radius: 20rpx;
          font-size: 22rpx;
          font-weight: 500;

          &.status-0 {
            background-color: #fff7e6;
            color: #fa8c16;
            border: 1rpx solid #ffd591;
          }

          &.approved {
            background-color: #f6ffed;
            color: #52c41a;
            border: 1rpx solid #b7eb8f;
          }

          &.rejected {
            background-color: #fff2f0;
            color: #ff4d4f;
            border: 1rpx solid #ffccc7;
          }
        }
      }
    }
  }

  .pending-empty {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 60rpx 0;

    .empty-text {
      font-size: 28rpx;
      color: #999;
    }
  }
}

/* 位置信息样式 */
.location-section {
  margin-top: 20rpx;
  background-color: #fff;
  padding: 20rpx;

  .location-header {
    padding-bottom: 20rpx;
    margin-bottom: 20rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .location-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .location-content {
    .location-text {
      font-size: 28rpx;
      color: #333;
      line-height: 1.6;
      margin-bottom: 16rpx;
    }

    .map-container {
      width: 100%;
      border-radius: 8rpx;
      overflow: hidden;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    }
  }
}
</style>
